@{
    ViewData["Title"] = "库存交易统计";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>物料库存统计</h3>
                </div>
                <div class="layui-card-body">
                    <!-- 搜索条件 -->
                    <div class="layui-form layui-form-pane" lay-filter="searchForm">
                        <div class="layui-row layui-col-space10">
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">仓库</label>
                                    <div class="layui-input-block">
                                        <select name="warehouseId" id="warehouseId">
                                            <option value="">全部仓库</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">物料分类</label>
                                    <div class="layui-input-block">
                                        <select name="materialClassId" id="materialClassId">
                                            <option value="">全部分类</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">物料关键字</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="materialKeyword" placeholder="物料编码/名称" autocomplete="off" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">月份</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="queryMonth" id="queryMonth" placeholder="选择月份" autocomplete="off" class="layui-input">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="margin-left: 0; text-align: center;">
                                <button class="layui-btn" lay-submit lay-filter="search">
                                    <i class="layui-icon layui-icon-search"></i> 查询
                                </button>
                                <button type="reset" class="layui-btn layui-btn-primary">
                                    <i class="layui-icon layui-icon-refresh"></i> 重置
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 图表工具栏 -->
                    <div class="layui-row">
                        <div class="layui-col-md12">
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    交易数量统计
                                    <div class="layui-btn-group" style="float:right;">
                                        <button type="button" class="layui-btn layui-btn-sm" id="btnLine">折线图</button>
                                        <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="btnBar">柱状图</button>
                                    </div>
                                </div>
                                <div class="layui-card-body">
                                    <!-- 图表容器 -->
                                    <div id="chartMain" class="chart-container">
                                        <div class="chart-loading">加载中...</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
<style>
    .chart-container {
        height: 400px;
        margin: 15px 0;
        border: 1px solid #eee;
        padding: 10px;
    }
    .chart-loading {
        height: 400px;
        line-height: 400px;
        text-align: center;
        background-color: #f8f8f8;
    }
    .layui-form-label {
        width: 80px;
    }
    .layui-input-block {
        margin-left: 110px;
    }
</style>

<!-- 添加ECharts CDN引用 -->
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
<!-- 备用加载方案 -->
<script>
    if (!window.echarts) {
        document.write('<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"><\/script>');
    }
</script>

<script>
    layui.use(['form', 'laydate', 'layer'], function () {
        var form = layui.form;
        var laydate = layui.laydate;
        var layer = layui.layer;
        var $ = layui.jquery;
        
        var currentChartType = 'line';
        var statisticsData = null;
        var myChart = null;
        
        // 初始化日期选择器
        laydate.render({
            elem: '#queryMonth',
            type: 'month',
            value: new Date()
        });
        
        // 加载仓库下拉数据
        function loadWarehouses() {
            // 模拟数据，实际应该从接口获取
            var warehouses = [
                { id: 1, name: "原材料仓库" },
                { id: 2, name: "成品仓库" },
                { id: 3, name: "半成品仓库" }
            ];
            
            var warehouseSelect = $("#warehouseId");
            $.each(warehouses, function (index, item) {
                warehouseSelect.append('<option value="' + item.id + '">' + item.name + '</option>');
            });
            
            form.render('select');
        }
        
        // 加载物料分类下拉数据
        function loadMaterialClasses() {
            // 模拟数据，实际应该从接口获取
            var classes = [
                { id: 1, name: "电子元件" },
                { id: 2, name: "机械零部件" },
                { id: 3, name: "包装材料" }
            ];
            
            var classSelect = $("#materialClassId");
            $.each(classes, function (index, item) {
                classSelect.append('<option value="' + item.id + '">' + item.name + '</option>');
            });
            
            form.render('select');
        }
        
        // 加载初始数据
        loadWarehouses();
        loadMaterialClasses();
        
        // 初始化图表
        function initChart() {
            try {
                if (!window.echarts) {
                    console.error('ECharts未加载成功');
                    $('#chartMain').html('<div class="layui-bg-gray" style="height:400px;text-align:center;line-height:400px;"><i class="layui-icon layui-icon-face-cry" style="font-size: 30px;"></i> 图表加载失败，请刷新重试</div>');
                    return;
                }
                
                myChart = echarts.init(document.getElementById('chartMain'));
                loadStatisticsData();
                
                // 窗口大小改变时，重绘图表
                window.addEventListener('resize', function() {
                    if (myChart) {
                        myChart.resize();
                    }
                });
            } catch (e) {
                console.error('初始化图表出错:', e);
                $('#chartMain').html('<div class="layui-bg-gray" style="height:400px;text-align:center;line-height:400px;"><i class="layui-icon layui-icon-face-cry" style="font-size: 30px;"></i> 图表初始化失败</div>');
            }
        }
        
        // 切换图表类型
        function switchChartType(type) {
            currentChartType = type;
            if (myChart) {
                myChart.dispose();
            }
            
            myChart = echarts.init(document.getElementById('chartMain'));
            loadStatisticsData();
        }
        
        // 渲染图表
        function renderChart() {
            if (!statisticsData || !statisticsData.dailyStatistics || statisticsData.dailyStatistics.length === 0) {
                $('#chartMain').html('<div class="layui-bg-gray" style="height:400px;text-align:center;line-height:400px;">暂无数据</div>');
                return;
            }
            
            if (!myChart) {
                initChart();
                return;
            }
            
            var dates = [];
            var inboundData = [];
            var outboundData = [];
            
            $.each(statisticsData.dailyStatistics, function(i, item) {
                dates.push(item.date);
                inboundData.push(item.inboundQuantity);
                outboundData.push(item.outboundQuantity);
            });
            
            var option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                legend: {
                    data: ['入库数量', '出库数量']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: currentChartType === 'bar',
                    data: dates
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '入库数量',
                        type: currentChartType,
                        data: inboundData,
                        itemStyle: {
                            color: '#5FB878'
                        }
                    },
                    {
                        name: '出库数量',
                        type: currentChartType,
                        data: outboundData,
                        itemStyle: {
                            color: '#FF5722'
                        }
                    }
                ]
            };
            
            myChart.setOption(option);
        }
        
        // 加载统计数据
        function loadStatisticsData() {
            // 组装查询参数
            var queryData = {
                warehouseId: $("#warehouseId").val() || null,
                materialClassId: $("#materialClassId").val() || null,
                materialKeyword: $("input[name='materialKeyword']").val() || null,
                queryMonth: $("#queryMonth").val() ? new Date($("#queryMonth").val()) : new Date()
            };
            
            // 转换为数字类型
            if (queryData.warehouseId) queryData.warehouseId = parseInt(queryData.warehouseId);
            if (queryData.materialClassId) queryData.materialClassId = parseInt(queryData.materialClassId);
            
            // 显示加载层
            var loadIndex = layer.load(2);
            
            // 发送请求
            $.ajax({
                url: '/InventoryTransactionStatistics/GetStatistics',
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(queryData),
                success: function(res) {
                    layer.close(loadIndex);
                    
                    if (res && res.code === 0) {
                        statisticsData = res.data;
                        renderChart();
                    } else {
                        // 尝试使用模拟数据
                        useMockData(queryData);
                    }
                },
                error: function(xhr) {
                    layer.close(loadIndex);
                    console.error("API请求错误:", xhr);
                    // 尝试使用模拟数据
                    useMockData(queryData);
                }
            });
        }
        
        // 使用模拟数据
        function useMockData(queryData) {
            
            $.ajax({
                url: '/InventoryTransactionStatistics/GetStatisticsMock',
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(queryData),
                success: function(res) {
                    if (res && res.code === 0) {
                        statisticsData = res.data;
                        renderChart();
                    } else {
                        layer.msg('获取模拟数据失败: ' + (res ? res.msg : '未知错误'), {icon: 2});
                    }
                },
                error: function() {
                    // 所有方法都失败，使用本地生成的模拟数据
                    generateLocalMockData(queryData);
                }
            });
        }
        
        // 本地生成模拟数据（当所有API都失败时）
        function generateLocalMockData(queryData) {
            console.log("生成本地模拟数据");
            var result = { dailyStatistics: [] };
            var date = queryData.queryMonth ? new Date(queryData.queryMonth) : new Date();
            var daysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
            
            for (var i = 1; i <= daysInMonth; i++) {
                var dayDate = new Date(date.getFullYear(), date.getMonth(), i);
                var inbound = Math.floor(Math.random() * 150) + 50; // 50-200之间随机数
                var outbound = Math.floor(Math.random() * 150) + 30; // 30-180之间随机数
                
                result.dailyStatistics.push({
                    date: dayDate.getFullYear() + '-' + 
                          String(dayDate.getMonth() + 1).padStart(2, '0') + '-' + 
                          String(dayDate.getDate()).padStart(2, '0'),
                    inboundQuantity: inbound,
                    outboundQuantity: outbound
                });
            }
            
            statisticsData = result;
            renderChart();
        }
        
        // 绑定事件
        form.on('submit(search)', function(data) {
            loadStatisticsData();
            return false;
        });
        
        $('#btnLine').click(function() {
            $(this).removeClass('layui-btn-primary');
            $('#btnBar').addClass('layui-btn-primary');
            switchChartType('line');
        });
        
        $('#btnBar').click(function() {
            $(this).removeClass('layui-btn-primary');
            $('#btnLine').addClass('layui-btn-primary');
            switchChartType('bar');
        });
        
        // 页面加载完成后初始化
        $(document).ready(function() {
            initChart();
        });
    });
</script>
}